package com.jianyi.model;

import java.io.File;
import java.util.Date;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.upload.UploadFile;
import com.jianyi.util.FileUtil;
import com.jianyi.util.UUIDUtils;

public class FileInfo extends Model<FileInfo>{

	private static final long serialVersionUID = -3200245736769999928L;
	public static final FileInfo dao = new FileInfo();
	
	public File getFile(FileInfo fileInfo){
		if(fileInfo!=null){
			String path=PropKit.get("file.storePath");
			return new File(path+File.separator+fileInfo.getStr("fileName"));
		}
		return null;
	}
	
	public byte[] getBytes(FileInfo fileInfo){
		File f=getFile(fileInfo);
		return FileUtil.getBytes(f.getAbsolutePath());
	}
	
	public FileInfo add(UploadFile uploadFile,String userId){
		FileInfo fileInfo=new FileInfo();
		String id=UUIDUtils.getUUID();
		Date now=new Date();
		fileInfo.set("id", id);
		fileInfo.set("removed", "0");
		fileInfo.set("creator",userId);
		fileInfo.set("createTime", now);
		fileInfo.set("updator", userId);
		fileInfo.set("updateTime", now);
		fileInfo.set("originalFileName", uploadFile.getOriginalFileName());
		fileInfo.set("fileName", uploadFile.getFileName());
		fileInfo.set("contentType", uploadFile.getContentType());
		fileInfo.set("md5", FileUtil.getMd5ByFile(uploadFile.getFile()));
		fileInfo.save();
		return fileInfo;
	}

}
